from __future__ import annotations

import curses
from typing import List

from .accounts import load_accounts
from .events import read_owner_events
from .paths import get_memory_dir


def _draw_feed(stdscr, owner: str, limit: int = 50) -> None:
    stdscr.clear()
    h, w = stdscr.getmaxyx()
    title = f"Agent Workspace — {owner}'s space (q to quit)"
    stdscr.addstr(0, 0, title[: w - 1])

    events = read_owner_events(get_memory_dir(), owner, None)
    events.sort(key=lambda e: e.created_at, reverse=True)
    y = 2
    for e in events[:limit]:
        line = f"{e.created_at} [{e.type}] {e.actor}: "
        if e.type == "reaction":
            line += f"{e.headers.get('reaction','like')} -> {e.headers.get('in_reply_to','')}"
        elif e.type == "comment":
            line += e.content.replace("\n", " ")
        elif e.type == "footprint":
            line += e.headers.get("ctx", "")
        else:
            line += e.content.replace("\n", " ")
        for chunk in [line[i : i + (w - 1)] for i in range(0, len(line), w - 1)]:
            if y >= h - 1:
                break
            stdscr.addstr(y, 0, chunk)
            y += 1
        if y >= h - 1:
            break
    stdscr.refresh()


def run_tui() -> None:
    """Minimal curses feed viewer.

    - Up/Down: switch owner among known accounts
    - q: quit
    """

    store = load_accounts()
    owners: List[str] = sorted(store.accounts.keys())
    idx = owners.index(store.default_owner) if store.default_owner in owners else 0

    def _main(stdscr):
        nonlocal idx
        curses.curs_set(0)
        while True:
            _draw_feed(stdscr, owners[idx])
            c = stdscr.getch()
            if c in (ord("q"), ord("Q")):
                break
            elif c in (curses.KEY_DOWN, ord("j")):
                idx = (idx + 1) % len(owners)
            elif c in (curses.KEY_UP, ord("k")):
                idx = (idx - 1) % len(owners)

    curses.wrapper(_main)

